//调用websocket
var voice = require('../utils/voice.js')
function openWebSocket() {
  //return false
  wx.onSocketOpen(function () {
    wx.closeSocket()
  })

  var stoken = wx.getStorageSync('ystoken')
  console.log(stoken)
  wx.connectSocket({
    // url: 'ws://192.168.2.116:444',//测试环境
    url:'ws://ceshi7.sdykt.com.cn:1280',
    success: function (res) {
    }
  })
  wx.onSocketOpen(function (res) {
    console.log('WebSocket连接已打开！')
    wx.sendSocketMessage({
      data: stoken
    })
  })

  wx.onSocketError(function (res) {
    console.log('WebSocket连接打开失败，请检查！')
  })

  wx.onSocketMessage(function (res) {
    var json_arr = JSON.parse(res.data);
    var noice = json_arr.payed;
    wx.showToast({
      title: noice,
      icon: 'success',
      duration: 2000,
      mask:true,
    })
    console.log(json_arr)
    wx.getStorage({
      key: 'vtoken',
      success: function (res) {
        voice.requestVoice(res.data, noice)
      },
      fail: function (res) {
        voice.calVoice((err, res) => {
        })
      }
    })
  })
  var time = setInterval(function () {
    console.log('推送'+stoken)
    wx.sendSocketMessage({
      data: stoken
    })
  }, 60000)
}
module.exports = {
  openWebSocket: openWebSocket,
}

// var socketOpen = false
// var socketMsgQueue = []
// wx.connectSocket({
//   url: 'test.php'
// })

// wx.onSocketOpen(function (res) {
//   socketOpen = true
//   for (var i = 0; i < socketMsgQueue.length; i++) {
//     sendSocketMessage(socketMsgQueue[i])
//   }
//   socketMsgQueue = []
// })

// function sendSocketMessage(msg) {
//   if (socketOpen) {
//     wx.sendSocketMessage({
//       data: msg
//     })
//   } else {
//     socketMsgQueue.push(msg)
//   }
// }
